import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '../views/Login.vue'
import Home from '../views/Home.vue'
import Welcome from '../views/Welcome.vue'
import Users from '../views/Users.vue'
import Rights from '../views/Rights.vue'
import Roles from '../views/Roles.vue'

Vue.use(VueRouter)
// redirect重定向路由规则
const routes = [
  { path: '/', redirect: '/login' },
  { path: '/login', component: Login },
  {
    path: '/home',
    component: Home,
    redirect: '/welcome',
    // 子路由规则
    children: [
      { path: '/welcome', component: Welcome },
      { path: '/users', component: Users },
      { path: '/rights', component: Rights },
      { path: '/roles', component: Roles }
    ]
  }
]

const router = new VueRouter({
  routes
})

// 挂载全局路由导航守卫
router.beforeEach((to, from, next) => {
  // to将要到达的路径 from将要离开的路径 next放行的方法
  // 如果访问的是登录页 则直接放行
  if (to.path === '/login') next()
  // 如果检测到用户未登录 则直接跳转到登录页
  if (!window.sessionStorage.getItem('token')) next('/login')
  // 如果用户已登录 则直接放行
  next()
})

export default router
